package com.qingcheng.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.BrandMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.goods.Brand;
import com.qingcheng.service.goods.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

/**
 * Created by chendx on 2021/5/21.
 */
@Service(interfaceClass = BrandService.class)
@Transactional
public class BrandServiceImpl implements BrandService {

    @Autowired
    private BrandMapper brandMapper;

    @Override
    public List<Brand> findAll() {
        return brandMapper.selectAll();
    }

    @Override
    public Brand findById(Integer id) {
        return brandMapper.selectByPrimaryKey(id);
    }

    @Override
    public PageResult<Brand> findPage(Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Brand> brandPage = (Page<Brand>) brandMapper.selectAll();
        return new PageResult<>(brandPage.getTotal(),brandPage.getResult());
    }

    @Override
    public List<Brand> findByCondition(Map<String, Object> map) {
        List<Brand> brands = brandMapper.selectByExample(createExample(map));
        return brands;
    }

    @Override
    public PageResult<Brand> findByConditionPage(Map<String, Object> map, Integer currentPage, Integer pageSize) {
        Example example = createExample(map);
        PageHelper.startPage(currentPage,pageSize);
        Page<Brand> brands = (Page<Brand>) brandMapper.selectByExample(example);
        return new PageResult<>(brands.getTotal(),brands.getResult());
    }

    @Override
    public void insert(Brand brand) {
        brandMapper.insertSelective(brand);
    }

    @Override
    public void update(Brand brand) {
        brandMapper.updateByPrimaryKeySelective(brand);
    }

    @Override
    public void deleteById(Integer id) {
        brandMapper.deleteByPrimaryKey(id);
    }

    private Example createExample(Map<String, Object> map) {
        Example example = new Example(Brand.class);
        Example.Criteria criteria = example.createCriteria();
        if (map != null){
            if (map.get("name") != null){
                criteria.andLike("name", "%"+map.get("name")+"%");
            }
            if (map.get("letter") != null){
                criteria.andEqualTo("letter", (String)map.get("letter"));
            }
        }
        return example;
    }
}
